﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Transactions;

namespace ClientApp
{
    public partial class Form1 : Form
    {
        private Random rand;
        public Form1()
        {
            InitializeComponent();
            rand = new Random((int)DateTime.Now.Ticks);
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    MasterProxy.IMasterMaintenance masterProxy = new MasterProxy.MasterMaintenanceClient();
                    int masterId = masterProxy.InsertMasterRecord(txtMaster.Text);

                    //MessageBox.Show(String.Format("Master Id: [{0}]", masterId));

                    CauseRandomError();

                    DetailProxy.IDetailMaintenance detailProxy = new DetailProxy.DetailMaintenanceClient();
                    detailProxy.InsertDetailRecord(masterId, txtDetail.Text);

                    scope.Complete();

                    //MessageBox.Show(String.Format("Master Id: [{0}], Detail: [{1}]", masterId, txtDetail.Text));
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    String.Format("Error ocurred [{0}]", ex.Message), "Error!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CauseRandomError()
        {
            if (rand.Next(3) == 0)
            {
                throw new Exception("Sorry!");
            }
        }
    }
}